
(function ($, win, doc, body) {
    var supportedClient = true,
        supportedPositionFixed = true,
        supportedOverflowScroll = true,
        dialogClassname = "tl-dialog",
        $body = $(body),
        $page = $body.children("form:first"),
        $win = $(win),
        customizedDialogsCount = 0;

    // check client
    supportedClient = $.browser.msie && $.browser.version < 8 ? false : supportedClient;

    function customizeDialogOpen () {
        if (customizedDialogsCount === 0) {
            $body.addClass(dialogClassname);
            $page.css({
                width: $page.width(),
                position: supportedPositionFixed ? "fixed" : "absolute",
                left: $page.offset().left, //-$win.scrollLeft(),
                top: 0, //-$win.scrollTop()
                zIndex: 0
            });
        }

        var
            $element = this.uiDialog,
            $overlay = this.overlay.$el;
        $element.css({
            position: "relative"
        });
        $overlay.css({
            position: "fixed"
        });

        customizedDialogsCount++;
    }

    function customizeDialogClose () {
        customizedDialogsCount--;

        if (customizedDialogsCount === 0) {
            $body.removeClass(dialogClassname);
            $page.css({
                width: "auto",
                position: "static"
            });
        }
    }

    $.extend($, {
        tlDialog: function (tmplName, opts) {
            var defaultOpts = {
                modal: true,
                draggable: true,
                resizable: false,
                closeOnEscape: true,
                closeText: "Close",
                customizeDialogOpen: supportedClient ? customizeDialogOpen : null,
                customizeDialogClose: supportedClient ? customizeDialogClose : null,
                buttons: [
                    {
                        text: "Cancel",
                        click: function (evt) {
                            $(this).dialog("close");
                        }
                    }
                ],
                tmplData: {}
            };

            if (opts && typeof opts === "object" && opts.hasOwnProperty("buttons") && $.isArray(opts.buttons)) {
                var buttons = defaultOpts.buttons;
                for (var i = 0, n = buttons.length; i < n; i++) {
                    opts.buttons.push(buttons[i]);
                }
            }

            opts = $.extend(defaultOpts, opts);

            return $.tlTmpl(tmplName, opts.tmplData).dialog(opts);
        }
    });
})(jQuery, window, document, document.body);
